package dao;

import bean.Person;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;
import java.util.Objects;

public class PersonDAOImpl extends HibernateDaoSupport implements PersonDAO {
    @Override
    public void save(Person person) {
        try {
            Objects.requireNonNull(getHibernateTemplate()).save(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(Person temporary) {
        try {
            Person person = Objects.requireNonNull(getHibernateTemplate()).get(Person.class, temporary.getPersonId());
            Objects.requireNonNull(person).setPersonName(temporary.getPersonName());
            person.setSex(temporary.getSex());
            person.setBirthdate(temporary.getBirthdate());
            person.setAddress(temporary.getAddress());
            getHibernateTemplate().update(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delete(int personId) {
        try {
            Person person = query(personId);
            Objects.requireNonNull(getHibernateTemplate()).delete(person);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("unchecked")
    @Override
    public List<Person> query() {
        List<Person> persons;
        try {
            persons = (List<Person>) getHibernateTemplate().find("FROM bean.Person");
        } catch (Exception e) {
            persons = null;
            e.printStackTrace();
        }
        return persons;
    }

    @Override
    public Person query(int personId) {
        Person person;
        try {
            person = getHibernateTemplate().get(Person.class, personId);
        } catch (Exception e) {
            person = null;
            e.printStackTrace();
        }
        return person;
    }
}
